package TP;

import fr.inria.acacia.corese.api.IDatatype;
import fr.inria.acacia.corese.exceptions.EngineException;
import fr.inria.edelweiss.kgram.core.Mapping;
import fr.inria.edelweiss.kgram.core.Mappings;
import fr.inria.edelweiss.kgraph.core.Graph;
import fr.inria.edelweiss.kgraph.query.QueryProcess;
import fr.inria.edelweiss.kgraph.rule.RuleEngine;
import fr.inria.edelweiss.kgtool.load.Load;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author GaspardP <gaspardp@kth.se>
 */
@WebServlet(name = "indexServlet", urlPatterns = {"/index"})
public class IndexServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {

            // Récupération des options sur le serveur
            StringBuilder options = new StringBuilder();
            // - Si on a pas encore chargé les genres
            ServletContext context = getServletConfig().getServletContext();
            if (null == context.getAttribute("genres")) {
                // Initialisation des paramètres serveurs
                serverInit();
            }

            Map<String, String> genres = (Map<String, String>) context.getAttribute("genres");
            // label = label.substring(1, label.length() - 4);

            // Envoie au client
            request.setAttribute("genres", genres);
            request.setAttribute("lignes", "lignes");

            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }

    private void serverInit() {

        ServletContext context = getServletConfig().getServletContext();

        Map<String, String> genres = new HashMap<>();
        Graph graph = Server.getGraph(context);
        // Récupération des genres
        QueryProcess exec = QueryProcess.create(graph);
        String query = "SELECT ?label ?genre WHERE"
                + "{"
                + "?genre a <http://dbpedia.org/ontology/Genre>."
                + "?genre rdfs:label ?label."
                + "}";

        try {
            Mappings map = exec.query(query);
            for (Mapping m : map) {
                String genre = ((IDatatype)m.getValue("?genre")).getLabel();
                String label = ((IDatatype)m.getValue("?label")).getLabel();
                genres.put(genre, label);
            }
        } catch (EngineException ex) {
            Logger.getLogger(IndexServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        context.setAttribute("genres", genres);
        context.setAttribute("graph", graph);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
